<template>
  <div>
    <!-- Sidebar -->
    <div class="sidebar">
      <div style="padding: 24px 20px; border-bottom: 1px solid #e5e7eb;">
        <div style="display: flex; align-items: center;">
          <div style="width: 40px; height: 40px; border-radius: 10px; overflow: hidden; flex-shrink: 0;">
            <img src="../../../头像.jpg" alt="头像" style="width: 100%; height: 100%; object-fit: cover;" />
          </div>
          <div style="margin-left: 12px;">
            <div style="font-weight: 600; color: #111827;">快递代拿管理系统</div>
          </div>
        </div>
      </div>
      <div style="padding: 16px 0;">
        <div class="nav-section">主菜单</div>
        <button :class="['nav-item', $route.path === '/admin/dashboard' ? 'active' : '']" @click="$router.push('/admin/dashboard')"><i class="fas fa-chart-line"></i><span>数据总览</span></button>
        <button :class="['nav-item', $route.path === '/admin/orders' ? 'active' : '']" @click="$router.push('/admin/orders')"><i class="fas fa-box"></i><span>订单管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/users' ? 'active' : '']" @click="$router.push('/admin/users')"><i class="fas fa-users"></i><span>下单者管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/couriers' ? 'active' : '']" @click="$router.push('/admin/couriers')"><i class="fas fa-motorcycle"></i><span>代拿者管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/finance' ? 'active' : '']" @click="$router.push('/admin/finance')"><i class="fas fa-wallet"></i><span>财务管理</span></button>
        <div class="nav-section">运营管理</div>
        <button :class="['nav-item', $route.path === '/admin/announcements' ? 'active' : '']" @click="$router.push('/admin/announcements')"><i class="fas fa-bullhorn"></i><span>公告管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/pricing' ? 'active' : '']" @click="$router.push('/admin/pricing')"><i class="fas fa-percentage"></i><span>盈利规则</span></button>
        
        <div class="nav-section">系统设置</div>
        <button :class="['nav-item', $route.path === '/admin/permissions' ? 'active' : '']" @click="$router.push('/admin/permissions')"><i class="fas fa-shield-alt"></i><span>权限管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/logs' ? 'active' : '']" @click="$router.push('/admin/logs')"><i class="fas fa-file-alt"></i><span>系统日志</span></button>
        <button :class="['nav-item', $route.path === '/admin/settings' ? 'active' : '']" @click="$router.push('/admin/settings')"><i class="fas fa-cog"></i><span>系统设置</span></button>
      </div>
      <div style="position: absolute; bottom: 0; left: 0; right: 0; padding: 20px; border-top: 1px solid #e5e7eb;">
        <div style="display: flex; align-items: center;">
          <div style="width: 40px; height: 40px; border-radius: 50%; background:#e5e7eb; display:flex; align-items:center; justify-content:center; color:#6b7280; font-weight:600;">管</div>
          <div style="margin-left: 12px; flex: 1;">
            <div style="font-weight: 500; color: #111827; font-size: 14px;">管理员</div>
            <div style="font-size: 12px; color: #9ca3af;">超级管理员</div>
          </div>
        </div>
        <button class="nav-item" @click="confirmLogout" style="margin-top:12px;"><i class="fas fa-sign-out-alt"></i><span>退出登录</span></button>
      </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
      <!-- Header -->
      <div style="background: white; border-bottom: 1px solid #e5e7eb; padding: 16px 32px; display: flex; align-items: center; justify-content: space-between;">
        <div></div>
        <div style="display: flex; align-items: center; gap: 16px;">
          <div style="position: relative;">
            <i class="fas fa-search" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #9ca3af;"></i>
            <input
              v-model="searchKeyword"
              type="text"
              placeholder="搜索订单编号、用户或骑手..."
              style="padding: 8px 12px 8px 36px; border: 1px solid #e5e7eb; border-radius: 8px; width: 260px; font-size: 14px;"
            >
          </div>
          <button @click="showFeedbackDialog = true" style="position: relative; padding: 8px 16px; background: #3b82f6; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; display: flex; align-items: center; gap: 8px;">
            <i class="fas fa-comments"></i>
            <span>用户反馈</span>
            <span v-if="unreadFeedbackCount > 0" style="position: absolute; top: -4px; right: -4px; background: #ef4444; color: white; border-radius: 50%; width: 18px; height: 18px; display: flex; align-items: center; justify-content: center; font-size: 10px; font-weight: 600;">{{ unreadFeedbackCount > 9 ? '9+' : unreadFeedbackCount }}</span>
          </button>
        </div>
      </div>

      <!-- Content -->
      <div style="padding: 32px;">
        <div style="margin-bottom: 32px;">
          <h1 style="font-size: 28px; font-weight: 700; color: #111827; margin-bottom: 8px;">数据总览</h1>
          <p style="color: #6b7280;">平台运营核心数据概览</p>
        </div>

        <!-- Stats Grid -->
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 24px; margin-bottom: 32px;">
          <div class="stat-card">
            <div style="display: flex; align-items: center; justify-content: space-between;">
              <div style="flex: 1;">
                <div class="stat-label">今日订单</div>
                <div class="stat-value">{{ formatNumber(stats.todayOrders) }}</div>
                <div class="stat-change" :class="stats.todayOrdersGrowth >= 0 ? 'positive' : 'negative'">
                  <i :class="stats.todayOrdersGrowth >= 0 ? 'fas fa-arrow-up' : 'fas fa-arrow-down'"></i>
                  <span>{{ Math.abs(stats.todayOrdersGrowth) }}% 较昨日</span>
                </div>
              </div>
              <div style="width: 56px; height: 56px; background: transparent; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                <!-- 订单图标：盒子 -->
                <svg viewBox="0 0 24 24" width="32" height="32" aria-hidden="true">
                  <path d="M4 7.5L12 3l8 4.5v9L12 21l-8-4.5v-9Z" fill="none" stroke="#3b82f6" stroke-width="1.7" stroke-linejoin="round"/>
                  <path d="M12 3v9" fill="none" stroke="#3b82f6" stroke-width="1.7" stroke-linejoin="round"/>
                </svg>
              </div>
            </div>
          </div>
          <div class="stat-card">
            <div style="display: flex; align-items: center; justify-content: space-between;">
              <div style="flex: 1;">
                <div class="stat-label">今日收入</div>
                <div class="stat-value">¥{{ formatMoney(stats.todayRevenue) }}</div>
                <div class="stat-change" :class="stats.todayRevenueGrowth >= 0 ? 'positive' : 'negative'">
                  <i :class="stats.todayRevenueGrowth >= 0 ? 'fas fa-arrow-up' : 'fas fa-arrow-down'"></i>
                  <span>{{ Math.abs(stats.todayRevenueGrowth) }}% 较昨日</span>
                </div>
              </div>
              <div style="width: 56px; height: 56px; background: transparent; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                <!-- 收入图标：人民币符号 -->
                <svg viewBox="0 0 24 24" width="32" height="32" aria-hidden="true">
                  <path d="M8 4h8M9.5 8.5l4-4m1 4l-4-4M12 8.5v9" fill="none" stroke="#10b981" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
                  <path d="M9 12h6" fill="none" stroke="#10b981" stroke-width="1.8" stroke-linecap="round"/>
                </svg>
              </div>
            </div>
          </div>
          <div class="stat-card">
            <div style="display: flex; align-items: center; justify-content: space-between;">
              <div style="flex: 1;">
                <div class="stat-label">活跃骑手</div>
                <div class="stat-value">{{ formatNumber(stats.activeCouriers) }}</div>
                <div class="stat-change" :class="stats.activeCouriersGrowth >= 0 ? 'positive' : 'negative'">
                  <i :class="stats.activeCouriersGrowth >= 0 ? 'fas fa-arrow-up' : 'fas fa-arrow-down'"></i>
                  <span>{{ Math.abs(stats.activeCouriersGrowth) }}% 较昨日</span>
                </div>
              </div>
              <div style="width: 56px; height: 56px; background: transparent; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                <!-- 骑手图标：小电动车 -->
                <svg viewBox="0 0 24 24" width="32" height="32" aria-hidden="true">
                  <circle cx="7" cy="17" r="2.6" fill="none" stroke="#a855f7" stroke-width="1.7"/>
                  <circle cx="17" cy="17" r="2.6" fill="none" stroke="#a855f7" stroke-width="1.7"/>
                  <path d="M9 17h4.5l2.5-6h-3.5l-1.5-3H8" fill="none" stroke="#a855f7" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
              </div>
            </div>
          </div>
          <div class="stat-card">
            <div style="display: flex; align-items: center; justify-content: space-between;">
              <div style="flex: 1;">
                <div class="stat-label">订单完成率</div>
                <div class="stat-value">{{ stats.completionRate.toFixed(1) }}%</div>
                <div class="stat-change" :class="stats.completionRateGrowth >= 0 ? 'positive' : 'negative'">
                  <i :class="stats.completionRateGrowth >= 0 ? 'fas fa-arrow-up' : 'fas fa-arrow-down'"></i>
                  <span>{{ Math.abs(stats.completionRateGrowth).toFixed(1) }}% 较昨日</span>
                </div>
              </div>
              <div style="width: 56px; height: 56px; background: transparent; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                <!-- 完成率图标：进度圆环 -->
                <svg viewBox="0 0 24 24" width="32" height="32" aria-hidden="true">
                  <circle cx="12" cy="12" r="7" fill="none" stroke="#f59e0b" stroke-width="1.7" stroke-opacity="0.35"/>
                  <path d="M12 5a7 7 0 0 1 6.3 4" fill="none" stroke="#f59e0b" stroke-width="1.9" stroke-linecap="round"/>
                  <path d="M9.2 12.2l1.9 1.9 3.8-3.8" fill="none" stroke="#f59e0b" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
              </div>
            </div>
          </div>
        </div>

        <!-- Charts with fixed height blocks -->
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 24px; margin-bottom: 32px;">
          <div class="chart-container">
            <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px;">
              <h3 style="font-size: 18px; font-weight: 600; color: #111827;">订单趋势</h3>
              <select v-model="orderTrendPeriod" @change="loadOrderTrend" style="padding: 6px 12px; border: 1px solid #e5e7eb; border-radius: 6px; font-size: 14px; color: #6b7280;">
                <option value="week">本周</option>
                <option value="month">本月</option>
                <option value="year">本年</option>
              </select>
            </div>
            <div class="chart-body">
              <canvas id="orderTrendChart"></canvas>
            </div>
          </div>
          <div class="chart-container">
            <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px;">
              <h3 style="font-size: 18px; font-weight: 600; color: #111827;">收入分布</h3>
              <select v-model="incomeDistPeriod" @change="loadIncomeDistribution" style="padding: 6px 12px; border: 1px solid #e5e7eb; border-radius: 6px; font-size: 14px; color: #6b7280;">
                <option value="month">本月</option>
                <option value="quarter">本季度</option>
                <option value="year">本年</option>
              </select>
            </div>
            <div class="chart-body">
              <canvas id="incomeDistChart"></canvas>
            </div>
          </div>
        </div>
        
        <!-- Real-time Orders Table -->
        <div class="table-container">
          <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px;">
            <h3 style="font-size: 18px; font-weight: 600; color: #111827;">实时订单监控</h3>
            <button @click="refreshPage" style="padding: 8px 16px; background: #3b82f6; color: white; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; font-size: 14px;">
              <i class="fas fa-sync-alt"></i>
              <span>刷新</span>
            </button>
          </div>
          <table>
            <thead>
              <tr>
                <th>订单编号</th>
                <th>用户信息</th>
                <th>骑手信息</th>
                <th>订单状态</th>
                <th>订单金额</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="o in filteredOrders" :key="o.id">
                <td style="font-weight: 500;">{{ o.id }}</td>
                <td>
                  <div>{{ o.order_user_nickname || '-' }}</div>
                  <div style="font-size: 12px; color: #9ca3af;">{{ o.order_user_phone || '-' }}</div>
                </td>
                <td>
                  <div>{{ o.courier_nickname || '-' }}</div>
                  <div style="font-size: 12px; color: #9ca3af;">{{ o.courier_phone || '-' }}</div>
                </td>
                <td><span class="status-badge" :class="statusClass(o.statusText)">{{ o.statusText }}</span></td>
                <td style="font-weight: 600; color: #111827;">¥{{ o.fee }}</td>
                <td>
                  <button
                    @click="openDetail(o.id)"
                    style="padding: 6px 12px; background: #f3f4f6; border: none; border-radius: 6px; cursor: pointer; font-size: 13px; color: #374151;"
                  >
                    查看详情
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 用户反馈对话窗口 -->
      <div v-if="showFeedbackDialog" style="position:fixed; inset:0; background:rgba(0,0,0,.4); display:flex; align-items:center; justify-content:center; z-index:1000; padding:16px;">
        <div style="background:#ffffff; width:720px; max-width:100%; max-height:85vh; border-radius:16px; box-shadow:0 25px 50px -12px rgba(0,0,0,0.25); display:flex; flex-direction:column; overflow:hidden;">
          <!-- 对话框头部 -->
          <div style="padding:24px 28px 20px; border-bottom:1px solid #e5e7eb; display:flex; align-items:flex-start; justify-content:space-between;">
            <div>
              <h3 style="font-size:20px; font-weight:700; color:#111827; margin:0 0 4px;">用户反馈</h3>
              <p style="font-size:14px; color:#6b7280; margin:0;">代拿者和下单者的反馈消息</p>
            </div>
            <button
              @click="showFeedbackDialog = false"
              style="margin-left:16px; padding:6px; border:none; background:#f3f4f6; border-radius:9999px; cursor:pointer; display:flex; align-items:center; justify-content:center; color:#9ca3af; transition:background-color .15s ease, color .15s ease;"
              onmouseover="this.style.backgroundColor='#e5e7eb'; this.style.color='#4b5563';"
              onmouseout="this.style.backgroundColor='#f3f4f6'; this.style.color='#9ca3af';"
            >
              <svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true">
                <path d="M6 18L18 6M6 6l12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
              </svg>
            </button>
          </div>

          <!-- 反馈列表区域 -->
          <div style="flex:1; padding:16px 20px 20px; background:#f9fafb; overflow-y:auto;">
            <div v-if="feedbackMessages.length === 0" style="text-align:center; padding:48px 16px; color:#9ca3af;">
              <i class="fas fa-inbox" style="font-size:40px; margin-bottom:12px; opacity:0.5;"></i>
              <p style="margin:0; font-size:14px;">暂无反馈消息</p>
            </div>

            <div
              v-for="(msg, index) in feedbackMessages"
              :key="index"
              style="margin-bottom:16px; border-radius:12px; background:#ffffff; border:1px solid #e5e7eb; padding:16px 16px 14px 18px; overflow:hidden; box-shadow:0 1px 2px rgba(0,0,0,0.04);"
            >
              <!-- 顶部信息 -->
              <div style="display:flex; align-items:flex-start; justify-content:space-between; margin-bottom:8px;">
                <div>
                  <div style="display:flex; align-items:center; gap:8px; margin-bottom:2px;">
                    <span style="font-weight:700; font-size:15px; color: #111827;">{{ msg.userName || '匿名用户' }}</span>
                    <span
                      style="padding:2px 6px; border-radius:9999px; font-size:11px; font-weight:500; background:#eff6ff; color:#1d4ed8;"
                    >
                      {{ msg.userType === 'courier' ? '代拿者' : '下单者' }}
                    </span>
                  </div>
                  <div style="font-size:12px; color:#9ca3af;">
                    {{ formatFeedbackTime(msg.createdAt || msg.created_at) }}
                  </div>
                </div>
                <!-- 未读红点 -->
                <div v-if="!msg.isRead && !msg.is_read" style="height:10px; width:10px; border-radius:9999px; background:#ef4444; box-shadow:0 0 0 4px rgba(248,113,113,0.25);"></div>
              </div>

              <!-- 反馈内容 -->
              <div style="margin-bottom:10px; color:#374151; font-size:14px; line-height:1.6; white-space:pre-wrap;">
                {{ msg.content }}
              </div>

              <!-- 联系方式 -->
              <div
                v-if="msg.contact"
                style="margin-bottom:10px; padding-top:8px; border-top:1px dashed #e5e7eb; font-size:12px; color:#6b7280; display:flex; align-items:center; gap:6px;"
              >
                <span style="display:inline-flex; align-items:center; justify-content:center; width:18px; height:18px; border-radius:9999px; background:#eff6ff; color:#3b82f6;">
                  <i class="fas fa-phone" style="font-size:10px;"></i>
                </span>
                <span>联系方式：</span>
                <span style="font-family:monospace; color:#111827;">{{ msg.contact }}</span>
              </div>

              <!-- 操作按钮 -->
              <div style="display:flex; gap:8px; margin-top:6px;">
                <button
                  v-if="!msg.isRead && !msg.is_read"
                  @click="markAsRead(msg.id)"
                  style="padding:6px 12px; background:#3b82f6; color:#ffffff; border:none; border-radius:9999px; font-size:12px; font-weight:500; cursor:pointer; box-shadow:0 1px 2px rgba(59,130,246,0.35);"
                >
                  标记已读
                </button>
                <button
                  @click="replyToFeedback(msg)"
                  style="padding:6px 12px; background:#10b981; color:#ffffff; border:none; border-radius:9999px; font-size:12px; font-weight:500; cursor:pointer; box-shadow:0 1px 2px rgba(16,185,129,0.35);"
                >
                  回复
                </button>
                <button
                  @click="deleteFeedback(msg.id)"
                  style="padding:6px 12px; background:#ef4444; color:#ffffff; border:none; border-radius:9999px; font-size:12px; font-weight:500; cursor:pointer; box-shadow:0 1px 2px rgba(239,68,68,0.35);"
                >
                  删除
                </button>
              </div>
            </div>
          </div>

          <!-- 发送回复 -->
          <div v-if="replyingTo" style="padding:14px 20px 16px; border-top:1px solid #e5e7eb; background:#f9fafb;">
            <div style="margin-bottom:6px; font-size:13px; color:#6b7280;">回复给：{{ replyingTo.userName || '匿名用户' }}</div>
            <textarea
              v-model="replyContent"
              placeholder="输入回复内容..."
              style="width:100%; min-height:80px; padding:10px 12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px; resize:none; font-family:inherit;"
            ></textarea>
            <div style="margin-top:10px; display:flex; justify-content:flex-end; gap:8px;">
              <button
                @click="cancelReply"
                style="padding:6px 14px; background:#e5e7eb; color:#374151; border:none; border-radius:9999px; font-size:13px; cursor:pointer;"
              >
                取消
              </button>
              <button
                @click="sendReply"
                style="padding:6px 16px; background:#3b82f6; color:#ffffff; border:none; border-radius:9999px; font-size:13px; font-weight:500; cursor:pointer;"
              >
                发送回复
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 详情弹窗 -->
      <div v-if="showDetail" style="position:fixed; inset:0; background:rgba(0,0,0,.4); display:flex; align-items:center; justify-content:center; z-index:1000;">
        <div style="width: 720px; max-width: 90%; background:#fff; border-radius:12px; padding:24px;">
          <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px;">
            <h3 style="font-size:18px; font-weight:600;">订单详情 #{{ detailOrder?.id }}</h3>
            <button @click="showDetail=false" style="border:0; background:transparent; font-size:20px; line-height:1; cursor:pointer;">×</button>
          </div>
          <div style="display:grid; grid-template-columns:1fr 1fr; gap:12px; font-size:14px; color:#374151;">
            <div><strong>下单者：</strong>{{ detailOrder?.order_user_nickname || '-' }}（{{ detailOrder?.order_user_phone || '-' }}）</div>
            <div><strong>代拿员：</strong>{{ detailOrder?.courier_nickname || '-' }}（{{ detailOrder?.courier_phone || '-' }}）</div>
            <div><strong>取件地址：</strong>{{ detailOrder?.pickup_location }}</div>
            <div><strong>送达地址：</strong>{{ detailOrder?.delivery_address }}</div>
            <div><strong>费用建议：</strong>¥{{ detailOrder?.suggested_fee ?? '-' }}</div>
            <div><strong>状态：</strong>{{ detailOrder?.statusText }}</div>
            <div style="grid-column:1/-1;"><strong>备注：</strong>{{ detailOrder?.note || '-' }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
  
</template>

<script>
import logo from '@/../头像.jpg'

// 避免 Chart 实例被 Vue 深度代理，使用模块级变量存放
let orderTrendChart = null
let incomeDistChart = null

export default {
  name: 'AdminDashboard',
  data() {
    return {
      logoUrl: logo || '',
      stats: {
        todayOrders: 0,
        todayOrdersGrowth: 0,
        todayRevenue: 0,
        todayRevenueGrowth: 0,
        activeCouriers: 0,
        activeCouriersGrowth: 0,
        completionRate: 0,
        completionRateGrowth: 0
      },
      orderTrendPeriod: 'week',
      incomeDistPeriod: 'month',
      recentOrders: [],
      searchKeyword: '',
      showDetail: false,
      detailOrder: null,
      showFeedbackDialog: false,
      feedbackMessages: [],
      unreadFeedbackCount: 0,
      replyingTo: null,
      replyContent: ''
    }
  },
  computed: {
    filteredOrders() {
      const kw = (this.searchKeyword || '').trim().toLowerCase();
      if (!kw) return this.recentOrders;
      return this.recentOrders.filter(o => {
        const fields = [
          String(o.id || ''),
          o.order_user_nickname || '',
          o.order_user_phone || '',
          o.courier_nickname || '',
          o.courier_phone || ''
        ].map(v => String(v).toLowerCase());
        return fields.some(v => v.includes(kw));
      });
    }
  },
  methods: {
    confirmLogout() {
      if (confirm('是否确认退出？')) {
        localStorage.removeItem('adminToken')
        localStorage.removeItem('adminInfo')
        localStorage.removeItem('userToken')
        this.$router.push('/login')
      }
    },
    refreshPage() {
      this.loadStats();
      this.loadOrderTrend();
      this.loadIncomeDistribution();
      this.loadRecentOrders();
    },
    formatNumber(num) {
      return (num || 0).toLocaleString();
    },
    formatMoney(num) {
      return (num || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    },
    async loadStats() {
      try {
        const res = await fetch('/api/admin/dashboard/stats');
        const data = await res.json();
        if (data && data.success) {
          this.stats = data.data || this.stats;
        }
      } catch (e) {
        console.error('加载统计数据失败', e);
      }
    },
    async loadOrderTrend() {
      try {
        const res = await fetch(`/api/admin/dashboard/order-trend?period=${this.orderTrendPeriod}`);
        const data = await res.json();
        if (data && data.success && orderTrendChart) {
          const raw = data.data || [];

          // 将后端日期转为 map，key=yyyy-mm-dd 或 yyyy-mm
          const countMap = new Map();
          raw.forEach(d => {
            const dt = new Date(d.date);
            if (Number.isNaN(dt.getTime())) return;
            const y = dt.getFullYear();
            const m = String(dt.getMonth() + 1).padStart(2, '0');
            const day = String(dt.getDate()).padStart(2, '0');
            if (this.orderTrendPeriod === 'year') {
              const key = `${y}-${m}`;
              countMap.set(key, (countMap.get(key) || 0) + (d.count || 0));
            } else {
              const key = `${y}-${m}-${day}`;
              countMap.set(key, (countMap.get(key) || 0) + (d.count || 0));
            }
          });

          const labels = [];
          const values = [];
          const today = new Date();

          if (this.orderTrendPeriod === 'week') {
            // 最近 7 天，按日期补 0
            for (let i = 6; i >= 0; i--) {
              const dt = new Date(today);
              dt.setDate(dt.getDate() - i);
              const y = dt.getFullYear();
              const m = String(dt.getMonth() + 1).padStart(2, '0');
              const d = String(dt.getDate()).padStart(2, '0');
              const key = `${y}-${m}-${d}`;
              labels.push(`${m}-${d}`);
              values.push(countMap.get(key) || 0);
            }
          } else if (this.orderTrendPeriod === 'month') {
            // 最近 30 天
            for (let i = 29; i >= 0; i--) {
              const dt = new Date(today);
              dt.setDate(dt.getDate() - i);
              const y = dt.getFullYear();
              const m = String(dt.getMonth() + 1).padStart(2, '0');
              const d = String(dt.getDate()).padStart(2, '0');
              const key = `${y}-${m}-${d}`;
              labels.push(`${m}-${d}`);
              values.push(countMap.get(key) || 0);
            }
          } else {
            // 年度：按月聚合，只显示有数据的月份，标签 YYYY-MM
            const sortedKeys = Array.from(countMap.keys()).sort();
            sortedKeys.forEach(key => {
              labels.push(key);
              values.push(countMap.get(key) || 0);
            });
          }

          orderTrendChart.data.labels = labels;
          orderTrendChart.data.datasets[0].data = values;
          orderTrendChart.update();
        }
      } catch (e) {
        console.error('加载订单趋势失败', e);
      }
    },
    async loadIncomeDistribution() {
      try {
        const res = await fetch(`/api/admin/dashboard/income-distribution?period=${this.incomeDistPeriod}`);
        const data = await res.json();
        if (data && data.success && incomeDistChart) {
          const dist = data.data || {};
          incomeDistChart.data.datasets[0].data = [
            dist.wechat || 0,
            dist.alipay || 0,
            dist.balance || 0,
            dist.other || 0
          ];
          incomeDistChart.update();
        }
      } catch (e) {
        console.error('加载收入分布失败', e);
      }
    },
    statusClass(status) {
      if (status === '待接单') return 'status-pending'
      if (status === '配送中') return 'status-processing'
      if (status === '已完成') return 'status-completed'
      if (status === '已取消') return 'status-cancelled'
      return ''
    },
    statusToText(code) {
      if (code === 1 || code === '1') return '待接单'
      if (code === 2 || code === '2') return '配送中'
      if (code === 3 || code === '3') return '已完成'
      if (code === 4 || code === '4') return '已取消'
      return code || '-'
    },
    async loadRecentOrders() {
      try {
        const res = await fetch('/api/orders?page=1&pageSize=5');
        const data = await res.json();
        if (data && data.success !== false) {
          this.recentOrders = (data.data || data).map(r => ({
            ...r,
            statusText: this.statusToText(r.status),
            fee: r.final_fee ?? r.suggested_fee ?? 0
          }))
        }
      } catch (e) {
        console.error('加载实时订单失败', e)
      }
    },
    async openDetail(id) {
      try {
        const res = await fetch(`/api/orders/${id}`);
        const data = await res.json();
        if (data && data.success !== false) {
          const d = data.data
          d.statusText = this.statusToText(d.status)
          this.detailOrder = d
          this.showDetail = true
        }
      } catch (e) {
        console.error('获取订单详情失败', e)
        alert('获取订单详情失败')
      }
    },
    async loadFeedbackMessages() {
      try {
        const res = await fetch('/api/admin/feedback')
        const data = await res.json()
        if (data && data.success !== false) {
          this.feedbackMessages = (data.data || data).sort((a, b) => {
            return new Date(b.createdAt || b.created_at) - new Date(a.createdAt || a.created_at)
          })
          this.unreadFeedbackCount = this.feedbackMessages.filter(m => !m.isRead && !m.is_read).length
        }
      } catch (e) {
        console.error('加载反馈消息失败', e)
      }
    },
    async markAsRead(id) {
      try {
        const res = await fetch(`/api/admin/feedback/${id}/read`, { method: 'PUT' })
        const data = await res.json()
        if (data && data.success !== false) {
          const msg = this.feedbackMessages.find(m => m.id === id)
          if (msg) {
            msg.isRead = true
            this.unreadFeedbackCount = Math.max(0, this.unreadFeedbackCount - 1)
          }
        }
      } catch (e) {
        console.error('标记已读失败', e)
        alert('操作失败')
      }
    },
    replyToFeedback(msg) {
      this.replyingTo = msg
      this.replyContent = ''
    },
    cancelReply() {
      this.replyingTo = null
      this.replyContent = ''
    },
    async sendReply() {
      if (!this.replyContent.trim()) {
        alert('请输入回复内容')
        return
      }
      try {
        const res = await fetch('/api/admin/feedback/reply', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            feedbackId: this.replyingTo.id,
            content: this.replyContent
          })
        })
        const data = await res.json()
        if (data && data.success !== false) {
          alert('回复成功')
          this.cancelReply()
          await this.loadFeedbackMessages()
        } else {
          alert(data.message || '回复失败')
        }
      } catch (e) {
        console.error('发送回复失败', e)
        alert('发送失败')
      }
    },
    async deleteFeedback(id) {
      if (!confirm('确定要删除这条反馈吗？')) return
      try {
        const res = await fetch(`/api/admin/feedback/${id}`, { method: 'DELETE' })
        const data = await res.json()
        if (data && data.success !== false) {
          this.feedbackMessages = this.feedbackMessages.filter(m => m.id !== id)
          this.unreadFeedbackCount = this.feedbackMessages.filter(m => !m.isRead && !m.is_read).length
        }
      } catch (e) {
        console.error('删除反馈失败', e)
        alert('删除失败')
      }
    },
    formatFeedbackTime(timeStr) {
      if (!timeStr) return ''
      const time = new Date(timeStr)
      const now = new Date()
      const diff = now - time
      const minutes = Math.floor(diff / 60000)
      if (minutes < 1) return '刚刚'
      if (minutes < 60) return `${minutes}分钟前`
      const hours = Math.floor(minutes / 60)
      if (hours < 24) return `${hours}小时前`
      const days = Math.floor(hours / 24)
      if (days < 7) return `${days}天前`
      return time.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })
    }
  },
  mounted() {
    const ensureChartJs = () => new Promise((resolve) => {
      if (window.Chart) {
        resolve();
        return;
      }
      const script = document.createElement('script');
      // 使用 Chart.js v3 稳定版本，避免与 Vue 的响应式产生递归错误
      script.src = 'https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js';
      script.onload = () => resolve();
      document.body.appendChild(script);
    });

    // 加载统计数据
    this.loadStats();
    // 实时订单
    this.loadRecentOrders();
    // 加载反馈消息
    this.loadFeedbackMessages();
    // 定期刷新反馈消息
    setInterval(() => {
      this.loadFeedbackMessages();
    }, 30000); // 每30秒刷新一次

    ensureChartJs().then(() => {
      const orderCtx = document.getElementById('orderTrendChart').getContext('2d');
      orderTrendChart = new window.Chart(orderCtx, {
        type: 'line',
        data: {
          labels: [],
          datasets: [{
            label: '订单数量',
            data: [],
            borderColor: '#3b82f6',
            backgroundColor: 'rgba(59, 130, 246, 0.1)',
            tension: 0.4,
            fill: true,
            pointRadius: 4,
            pointBackgroundColor: '#3b82f6'
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: { legend: { display: false } },
          scales: {
            y: { beginAtZero: true, grid: { color: '#f3f4f6' } },
            x: { grid: { display: false } }
          }
        }
      });

      const incomeCtx = document.getElementById('incomeDistChart').getContext('2d');
      incomeDistChart = new window.Chart(incomeCtx, {
        type: 'doughnut',
        data: {
          labels: ['微信支付', '支付宝', '余额支付', '其他'],
          datasets: [{
            data: [0, 0, 0, 0],
            backgroundColor: ['#3b82f6', '#10b981', '#f59e0b', '#a855f7'],
            borderWidth: 0
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: { legend: { position: 'bottom', labels: { padding: 16, usePointStyle: true } } }
        }
      });

      // 加载图表数据
      this.loadOrderTrend();
      this.loadIncomeDistribution();
    });
  }
}
</script>

<style scoped>
.sidebar {
  position: fixed;
  left: 0;
  top: 0;
  width: 240px;
  height: 100vh;
  background: #fff;
  border-right: 1px solid #e5e7eb;
  overflow-y: auto;
}

.main-content {
  margin-left: 240px;
  min-height: 100vh;
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  color: #6b7280;
  text-decoration: none;
  transition: all 0.2s;
  cursor: pointer;
  width: 100%;
  background: transparent;
  border: 0;
  text-align: left;
}

.nav-item:hover {
  background: #f3f4f6;
  color: #3b82f6;
}

.nav-item.active {
  background: #eff6ff;
  color: #3b82f6;
  font-weight: 500;
}

.nav-item i {
  width: 20px;
  margin-right: 12px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.stat-value { font-size: 32px; font-weight: 700; color: #111827; margin: 12px 0; }
.stat-label { color: #6b7280; font-size: 14px; }
.stat-change { display: inline-flex; align-items: center; font-size: 13px; margin-top: 8px; }
.stat-change.positive { color: #10b981; }
.stat-change.negative { color: #ef4444; }
.stat-change i { margin-right: 4px; }

/* 固定高度的图表容器 */
.chart-container {
  background: white;
  border-radius: 12px;
  padding: 16px 24px 24px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  height: 340px; /* 固定块高度 */
  display: flex;
  flex-direction: column;
}

.chart-body {
  flex: 1;
  min-height: 0;
}

.chart-body canvas {
  width: 100% !important;
  height: 100% !important; /* 充满容器以避免向下延伸 */
}

.table-container {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  overflow-x: auto;
}

table { width: 100%; border-collapse: collapse; }
th { text-align: left; padding: 12px; color: #6b7280; font-weight: 500; font-size: 13px; border-bottom: 1px solid #e5e7eb; }
td { padding: 16px 12px; border-bottom: 1px solid #f3f4f6; color: #374151; }
.status-badge { display: inline-block; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 500; }
.status-pending { background: #fef3c7; color: #92400e; }
.status-processing { background: #dbeafe; color: #1e40af; }
.status-completed { background: #d1fae5; color: #065f46; }
.status-cancelled { background: #fee2e2; color: #991b1b; }
.nav-section { padding: 16px 20px 8px; font-size: 12px; color: #9ca3af; font-weight: 500; text-transform: uppercase; letter-spacing: 0.5px; }
</style>